import {User} from 'knex/types/tables';
import knex from '../db/sql'
import {Context, MetheodType, Next} from 'TYPE';
import UserController from './user.controller'
import {validateQuery} from '../parameter_m';
import {userDB} from '../db/sqltable/user.db';
import {postDB} from '../db/sqltable/post.db';
import {subareaDB} from '../db/sqltable/subarea.db';
import {userPostRelationDB} from '../db/sqltable/user_post_relation.db';
import {notificationDB} from '../db/sqltable/notification.db';
import {topicDB} from '../db/sqltable/topic.db';
import {userRelativeDB} from '../db/sqltable/user_relative.db';
export default class AdminController {

    static checkIsAdmin(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        const original = descriptor.value
        descriptor.value = async (ctx: Context, next: Next) => {
            ctx.body = {}
            await AdminController.isAdmin(ctx, null).then(async () => {
                if (ctx.cd !== 0) {
                    await next()
                } else {
                    return await original(ctx, next)
                }
            })
        }

    }
    static async isAdmin(ctx: Context, next: Next) {
        next = next || (() => {}) as any
        await UserController.hasLogin(ctx, null)

        if (ctx.user) {
            if (!ctx.user.is_admin) {
                ctx.cd = 1
                ctx.msg = "不是管理员！！"
            } else {
                ctx.cd = 0
                ctx.msg = "是管理员"
            }
        }
        await next()
    }

    @AdminController.checkIsAdmin
    @validateQuery({
        type: ['all', 'user', 'post', 'relationship', 'notification']
    })
    static async updateCache(ctx: Context, next: Next) {
        const {type} = ctx.validatedParams
        if (type == 'user' || type == 'all') {
            userDB.loadAll()
        }
        if (type == 'post' || type == 'all') {
            await Promise.all([
                subareaDB.loadAll(),
                topicDB.loadAll(),
                postDB.loadAll(),
            ])
            await subareaDB.afterLoad()
        }
        if (type == 'relationship' || type == 'all') {
            userPostRelationDB.loadAll()
            userRelativeDB.loadAll()
        }
        if (type == 'notification' || type == 'all') {
            notificationDB.loadAll()
        }
        ctx.cd = 0
        ctx.msg = "更新缓存成功"
        next()
    }
}
